import Axios from 'axios';
import { provide } from 'vue';
import { useLoginUserStore } from '../../store';
import ApiConfig from './apiconfig';

const instance = Axios.create({
    baseURL: "",
    timeout: 100000,
    headers: {
        'Content-Type': 'application/json', // 设置请求头为 JSON
    },
});

//请求拦截
instance.interceptors.request.use(
    function (config) {
        const loginUserStore = useLoginUserStore();
        if (loginUserStore.token) {
            config.headers.Authorization = `Bearer ${loginUserStore.token}`;
        }
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

//返回拦截器
instance.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        //错误重定向处理
        return Promise.reject(error);
    }
);

//get请求方法
function get(url: string, params?: any, headers?: any, responseType?: any) {
    let fullUrl = `${url}`;
    if (params) {
        let queryParams = Object.keys(params).map(key => `${params[key]}`).join('/');
        fullUrl = ` ${url}/${queryParams}`;
    }
    return instance.get(fullUrl, { headers, responseType });
}
//post请求方法
function post(url: string, params?: any, headers?: any, responseType?: any) {
    return instance.post(url, params, { headers, responseType });
}

const API = {
    request(type: any, url: any, params?: any, headers?: any, responseType?: any) {
        switch (type) {
            case ApiConfig.Methods.GET:
                return get(url, params, headers, responseType);
            case ApiConfig.Methods.POST:
                return post(url, params, headers, responseType);
            default:
                return Promise.reject(new Error('Unsupported request type'));
        }
    }
}

export function provideApi() {
    provide('API', API);
    provide('ApiConfig', ApiConfig);
}